import React, { useRef } from 'react';
import debounce from 'lodash/debounce';
import moment from 'moment';
import PropTypes from 'prop-types';
import { Form, DatePicker, Input, Row, Col, Select, Spin } from 'antd';
import request from '@/utils/request';
import { SelectForm } from '@/components/UserForm';
import { getpostlistbycondition } from '@/services/components/userform';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import useTreeSelectData from '@/hooks/useTreeSelectData';
import TreeComponent from './TreeComponent';
import { useDepartmentList, useJobList, useEmployeeList, useCompanyList } from './utils';

const { Item } = Form;
const { Option } = Select;

// 可选择当天or本年之后的日期，日期只可选择本年的，不可选择第二年的时间
const disabledDate = current => current && (current < moment().startOf('day') || current > moment().endOf('year'));

const findCompany = (data, id) => {
    let result = '';
    const find = tree => {
        tree.forEach(item => {
            if (item.id === id) {
                result = item;
            } else if (Array.isArray(item.children)) {
                find(item.children);
            }
        });
    };

    find(data);

    return result;
};

const getDepartmentList = async params => {
    const res = await request('/api/org/v1/functional/list', {
        params
    });
    return res;
};

// 员工发起申请
const OwnApply = props => {
    const { form, type, detail } = props;
    const {
        employeeName,
        employeeId,
        companyId,
        companyName,
        preDepartmentId,
        preDepartmentName,
        prePostName,
        postGradeCode,
        prePostId,
        afterPostGradeCode,
        prePostGradeCode,
        // 他人调岗发起者 companyId
        applyCompanyId
    } = detail;
    const isOtherPost = type === 'other';
    const companyRef = useRef({ companyId });
    if (companyId !== companyRef.current.companyId) {
        companyRef.current = { companyId };
    }
    const [companyTreeData, companyTreeLoading] = useTreeSelectData('company');
    const [departmentTreeData, departmentTreeLoading] = useTreeSelectData('department', companyRef.current);
    const [departmentTreeAfterData, departmentTreeAfterLoading] = useTreeSelectData('department', companyRef.current);
    const { getFieldDecorator } = form;
    const { loading: employeeLoading, data: employeeList, getEmployeeList } = useEmployeeList({
        companyId: isOtherPost ? applyCompanyId : companyId
    });
    const { companyList } = useCompanyList({});
    // 调岗前部门列表
    const { treeData: preDepartTreeData } = useDepartmentList({
        companyId: isOtherPost ? form.getFieldValue('companyId') || applyCompanyId : companyId
    });
    // 调岗前职位列表
    const { loading: preJobLoading, treeData: preJobTreeData } = useJobList({
        companyId: isOtherPost ? form.getFieldValue('companyId') || applyCompanyId : companyId
    });

    const [postList, setPostList] = React.useState([]);
    const [curEmployeeRankName, setCurEmployeeRankName] = React.useState('');
    // // 调岗后部门列表
    // const { loading, treeData } = useDepartmentList({
    //     companyId: applyCompanyId || companyId
    // });
    // // 调岗后职位列表
    // const { loading: jobLoading, treeData: jobTreeData } = useJobList({
    //     companyId: applyCompanyId || companyId
    // });
    const handleEmployeeSearch = debounce(name => {
        getEmployeeList({
            companyId: isOtherPost ? applyCompanyId : companyId,
            userName: name
        });
    }, 500);
    const handleEmployeeChange = curEmployeeId => {
        const find = employeeList.find(item => item.id === curEmployeeId);
        if (find) {
            form.setFieldsValue({
                preDepartmentId: find.departmentId,
                prePostId: find.postId,
                companyId: find.companyId,
                employeeName: find.employeeName,
                userNo: find.userNo,
                postGradeCode: find.postGradeCode
            });
            const findCurCompany = findCompany(companyList, find.companyId);
            form.setFieldsValue({
                companyName: findCurCompany ? findCurCompany.companyName : ''
            });
            // TODO 后端不给，只能根据这个员工查询该员工所在部门列表，还得在请求一遍？
            getDepartmentList({
                companyId: find.companyId
            }).then(res => {
                if (res && res.code === 10000) {
                    const findDepartment = findCompany(res.data, find.departmentId);
                    form.setFieldsValue({
                        preDepartmentName: findDepartment ? findDepartment.departmentName : ''
                    });
                }
            });
            const findPost = preJobTreeData.find(item => item.id === find.postId);
            form.setFieldsValue({
                prePostName: findPost ? findPost.postName : ''
            });
        } else {
            form.setFieldsValue({
                preDepartmentId: '',
                prePostId: '',
                companyId: '',
                employeeName: '',
                postGradeCode: ''
            });
        }
    };
    const [departmentId, setDepartmentId] = React.useState('');

    const departmentChange = value => {
        setDepartmentId(value);
        form.resetFields('afterPostId');
    };

    const handleCompanyChange = curCompanyId => {
        const find = companyList.find(item => item.companyId === curCompanyId);

        if (find) {
            form.setFields({
                companyName: find.companyName
            });
        } else {
            form.setFields({
                companyName: ''
            });
        }
    };
    const renderEmployeeId = () =>
        getFieldDecorator('employeeId', {
            rules: [
                {
                    required: true,
                    message: '请输入员工姓名！'
                }
            ]
        })(
            <Select
                allowClear
                notFoundContent={employeeLoading ? <Spin size="small" /> : null}
                loading={employeeLoading}
                showSearch
                onSelect={handleEmployeeChange}
                placeholder="请输入员工姓名"
                showArrow={false}
                filterOption={false}
                onSearch={handleEmployeeSearch}
            >
                {employeeList.map(item => (
                    <Option key={item.id} value={item.id}>
                        {item.employeeName}
                    </Option>
                ))}
            </Select>
        );
    const renderTransferDate = () =>
        getFieldDecorator('transferDate', {
            rules: [
                {
                    required: true,
                    message: '请选择办理调岗日期！'
                }
            ]
        })(<DatePicker disabledDate={disabledDate} style={{ width: '100%' }} />);

    const getOther = () =>
        getFieldDecorator(
            'companyId',
            {}
        )(
            <TreeSelectPro
                loading={companyTreeLoading}
                showSearch
                disabled
                treeData={companyTreeData}
                onChange={handleCompanyChange}
            />
        );
    // 获取职级
    const getEmployeeRankName = value => {
        const curList = postList.find(item => item.id === value);
        setCurEmployeeRankName(curList.postGradeCode);
    };

    return (
        <div>
            <Item required={type === 'other'} label="员工姓名">
                {type === 'other' ? renderEmployeeId() : detail.employeeName || employeeName}
                {type !== 'other' &&
                    getFieldDecorator('employeeId', {
                        initialValue: employeeId
                    })(<Input type="hidden" />)}
                {getFieldDecorator('employeeName', {
                    initialValue: type !== 'other' ? employeeName : ''
                })(<Input type="hidden" />)}
            </Item>
            {getFieldDecorator('userNo', {})}
            <Item required={type !== 'detail'} label="办理调岗日期">
                {type !== 'detail' ? renderTransferDate() : detail.transferDate}
                {type === 'detail' &&
                    getFieldDecorator('transferDate', {
                        initialValue: moment(detail.transferDate)
                    })(<DatePicker style={{ width: '100%', display: 'none' }} />)}
            </Item>
            <Item required={type === 'other'} label="所属公司">
                {type === 'other' ? getOther() : companyName}
                {getFieldDecorator('companyId', {
                    initialValue: companyId
                })(<Input type="hidden" />)}
                {getFieldDecorator('companyName', {
                    initialValue: type !== 'other' ? companyName : ''
                })(<Input type="hidden" />)}
            </Item>
            <Item
                required={type !== 'detail'}
                style={type === 'other' ? { marginBottom: 0 } : {}}
                label="调岗前部门/职位/职级"
            >
                {type === 'other' ? (
                    <Row gutter={8}>
                        <Col span={8}>
                            <Item>
                                {getFieldDecorator(
                                    'preDepartmentId',
                                    {}
                                )(
                                    <TreeSelectPro
                                        loading={departmentTreeLoading}
                                        showSearch
                                        allowClear
                                        treeData={departmentTreeData}
                                        onChange={id => {
                                            const find = preDepartTreeData.find(item => item.id === id);

                                            if (find) {
                                                form.setFieldsValue({
                                                    afterDepartmentName: find.departmentName
                                                });
                                            } else {
                                                form.setFieldsValue({
                                                    afterDepartmentName: ''
                                                });
                                            }
                                        }}
                                    />
                                )}
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item>
                                {getFieldDecorator('prePostId', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择调岗后职位！'
                                        }
                                    ]
                                })(
                                    <TreeComponent
                                        disabled
                                        loading={preJobLoading}
                                        treeData={preJobTreeData}
                                        onChange={id => {
                                            const find = preJobTreeData.find(item => item.id === id);

                                            if (find) {
                                                form.setFieldsValue({
                                                    prePostName: find.postName
                                                });
                                            } else {
                                                form.setFieldsValue({
                                                    prePostName: ''
                                                });
                                            }
                                        }}
                                    />
                                )}
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item>{getFieldDecorator('postGradeCode')(<Input disabled />)}</Item>
                        </Col>
                    </Row>
                ) : (
                    `${preDepartmentName ? `${preDepartmentName}/` : ''}${prePostName || ''}${
                        postGradeCode ? `/${postGradeCode}` : ''
                    }${prePostGradeCode ? `/${prePostGradeCode}` : ''}`
                )}
                {getFieldDecorator('preDepartmentName', {
                    initialValue: type === 'other' ? '' : preDepartmentName
                })(<Input type="hidden" />)}
                {getFieldDecorator('prePostName', {
                    initialValue: type === 'other' ? '' : prePostName
                })(<Input type="hidden" />)}
                {type !== 'other' &&
                    getFieldDecorator('preDepartmentId', {
                        initialValue: preDepartmentId
                    })(<Input type="hidden" />)}
                {type !== 'other' &&
                    getFieldDecorator('prePostId', {
                        initialValue: prePostId
                    })(<Input type="hidden" />)}
            </Item>
            <Item
                required={type !== 'detail'}
                style={type !== 'detail' ? { marginBottom: 0 } : {}}
                label="调岗后部门/职位/职级"
            >
                {type !== 'detail' ? (
                    <Row gutter={8}>
                        <Col span={8}>
                            <Item>
                                {getFieldDecorator('afterDepartmentId')(
                                    // <CascaderForm
                                    //     getData={() =>
                                    //         request('/api/org/v1/functional/list').then(res => {
                                    //             if (res && res.code === 10000 && res.data) {
                                    //                 return res.data || [];
                                    //             }
                                    //             return [];
                                    //         })
                                    //     }
                                    //     fieldsName={{
                                    //         selectValue: 'id',
                                    //         selectTitle: 'departmentName',
                                    //         selectChildren: 'children'
                                    //     }}
                                    //     onChange={departmentChange}
                                    //     selectProps={{
                                    //         placeholder: '请选择部门',
                                    //         displayRender: label => clone(label).pop(),
                                    //         changeOnSelect: true,
                                    //         expandTrigger: 'hover'
                                    //     }}
                                    // />
                                    <TreeSelectPro
                                        loading={departmentTreeAfterLoading}
                                        showSearch
                                        allowClear
                                        treeData={departmentTreeAfterData}
                                        placeholder="请选择部门"
                                        onChange={departmentChange}
                                    />
                                )}
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item>
                                {getFieldDecorator('afterPostId', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择调岗后职位！'
                                        }
                                    ]
                                })(
                                    <SelectForm
                                        params={{ departmentId }}
                                        getData={params =>
                                            getpostlistbycondition(params).then(res => {
                                                if (res && res.code === 10000 && res.data) {
                                                    setPostList(res.data);
                                                    return res.data || [];
                                                }
                                                return [];
                                            })
                                        }
                                        fieldsName={{
                                            selectValue: 'id',
                                            selectTitle: 'postName'
                                        }}
                                        // onChange={this.companyChange}
                                        selectProps={{
                                            placeholder: '请选择应聘职位'
                                        }}
                                        onChange={getEmployeeRankName}
                                    />
                                )}
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item>
                                <Input disabled value={curEmployeeRankName} />
                            </Item>
                        </Col>
                    </Row>
                ) : (
                    `${detail.afterDepartmentName ? `${detail.afterDepartmentName}/` : ''}${detail.afterPostName ||
                        ''}${afterPostGradeCode ? `/${afterPostGradeCode}` : ''}`
                )}
                {getFieldDecorator('afterDepartmentName', {
                    initialValue: type !== 'detail' ? '' : detail.afterDepartmentName
                })(<Input type="hidden" />)}
                {getFieldDecorator('afterPostName', {
                    initialValue: type !== 'detail' ? '' : detail.afterPostName
                })(<Input type="hidden" />)}
                {type === 'detail' &&
                    getFieldDecorator('afterDepartmentId', {
                        initialValue: detail.afterDepartmentId
                    })(<Input type="hidden" />)}
                {type === 'detail' &&
                    getFieldDecorator('afterPostId', {
                        initialValue: detail.afterPostId
                    })(<Input type="hidden" />)}
            </Item>
        </div>
    );
};

OwnApply.propTypes = {
    /**
     * detail: 详细
     * other: 他人发起
     * edit: 员工发起
     */
    type: PropTypes.oneOf(['edit', 'detail', 'other']).isRequired
};

export default OwnApply;
